<template>
    <div class="vue-ms-main  vue-ms-main-add" v-loading="loading" style="padding: 0px;">
        <!--<b @click="getData()">数据获取</b>-->
        <div class="container info">
            <!--<b class="closebtns" @click="btnclose(true)">内容显示</b>-->
            <div class="right-container" v-if="selDataStu"> <!--closeStu-->
                <b class="closebtn" @click="btnclose(false)">关闭</b>
                <div class="gantt-selected-info">
                    <div>
                        <b>{{selectedTask.projectName}}</b>
                        <p>项目描述：{{selectedTask.text}}</p>
                        <p>项目进度:{{selectedTask.progress|toPercent}}%</p>
                        <p>项目级别: <span v-if="selectedTask.priority == 1" style="color: #ec1d1d;">一级</span>
                            <span v-if="selectedTask.priority == 2" style="color: #0063fd">二级</span>
                            <span v-if="selectedTask.priority == 3" style="color: #718cf3">三级</span>
                        </p>
                        <p>工作时间：{{selectedTask.duration}}小时</p>
                        <p>开始时间:{{selectedTask.start_date|niceDate}}</p>
                        <p>结束时间:{{selectedTask.end_date|niceDate}}</p>
                    </div>
                </div>
                <ul class="gantt-messages">
                    <li class="gantt-message" v-for="message in messages">{{message}}</li>
                </ul>
            </div>
            <!--"ID":'',-->
            <!--"projectName":'',-->
            <!--"text":'',-->
            <!--"Location":'',-->
            <!--"type":'',-->
            <!--"start_date": '',-->
            <!--"end_date":'',-->
            <!--"duration":'',-->
            <!--"progress":'',-->
            <!--"owner_id":'',-->
            <!--"parent":'',-->
            <!--"priority":'',-->
            <!--"hookURL":'',-->
            <!--"operator":'',-->
            <!--项目操作-->
            <!--<div class = "ms-updmain">-->
                <!--<el-form :model="addParams" status-icon ref="addParams" :rules="rules" label-width="100px" class="demo-ruleForm">-->
                    <!--<div class="info">-->
                        <!--<el-form-item label="项目名称" prop="projectName" ><i class="xing">*</i>-->
                            <!--<el-input type="text" v-model="addParams.projectName"  placeholder="请填写项目名称" auto-complete="on"></el-input>-->
                        <!--</el-form-item>-->
                        <!--<el-form-item label="开始时间" prop="start_date"><i class="xing">*</i>-->
                            <!--<el-date-picker v-model="addParams.start_date"  align="right" type="datetime"  placeholder="选择日期" :picker-options="pickerOptions1"></el-date-picker>-->
                        <!--</el-form-item>-->
                        <!--<el-form-item label="结束时间" prop="end_date"><i class="xing">*</i>-->
                            <!--<el-date-picker v-model="addParams.end_date" align="right" type="datetime"  placeholder="选择日期" :picker-options="pickerOptions1"></el-date-picker>-->
                        <!--</el-form-item>-->
                        <!--<el-form-item label="持续时间"  prop="duration"><i class="xing">*</i>-->
                            <!--<el-input type="text" v-model="addParams.duration"  placeholder="请填写持续时间" auto-complete="on"></el-input>-->
                        <!--</el-form-item>-->
                        <!--<el-form-item label="项目进度"  prop="progress"><i class="xing">*</i>-->
                            <!--<el-slider v-model="addParams.progress" show-input></el-slider>-->
                        <!--</el-form-item>-->
                        <!--<el-form-item label="优先级别"  prop="priority"><i class="xing">*</i>-->
                            <!--<el-select v-model="addParams.priority" filterable placeholder="请选择优先级别">-->
                                <!--<el-option v-for="item in priorityList" :key="item.value" :label="item.label" :value="item.value"></el-option>-->
                            <!--</el-select>-->
                        <!--</el-form-item>-->
                        <!--<el-form-item label="负责人员"  prop="owner_id"><i class="xing">*</i>-->
                            <!--<el-select v-model="addParams.owner_id" filterable placeholder="请选择优先级别">-->
                            <!--<el-option v-for="item in userList" :key="item.value" :label="item.label" :value="item.value"></el-option>-->
                            <!--</el-select>-->
                        <!--</el-form-item>-->
                        <!--<el-form-item label="项目描述" prop="text"><i class="xing">*</i>-->
                            <!--<el-input type="textarea" v-model="addParams.text" placeholder="请填写项目描述" auto-complete="off"></el-input>-->
                        <!--</el-form-item>-->
                        <!--<el-form-item>-->
                            <!--<el-button type="primary" @click="submitForm('ruleForm')">保存</el-button>-->
                            <!--<el-button @click="resetForm('ruleForm')">重置</el-button>-->
                            <!--<el-button type="primary" @click="submitForm('ruleForm')">关闭</el-button>-->
                            <!--<el-button type="primary" @click="submitForm('ruleForm')">删除</el-button>-->
                        <!--</el-form-item>-->
                    <!--</div>-->
                <!--</el-form>-->
            <!--</div>-->


            <!--列表-->
            <div ref="gantt" :style="dtable"></div>

            <div class="info" style="max-width: 350px; padding-bottom: 500px; overflow:hidden;margin-top: 20px;">
                <el-upload
                        class="upload-demo"
                        ref="upload"  drag
                        :action="uploadFileUrl"
                        on-success="uploadSuccess"
                        on-error="uploadError"
                        :on-preview="handlePreview"
                        :on-remove="handleRemove"
                        :show-file-list="true"
                        :file-list="fileList"
                        :on-success="handleAvatarSuccess"
                        :before-upload="beforeAvatarUpload"
                        :auto-upload="false">
                    <el-button style="background: transparent; color: #ccc; border: none; margin-top:56px;" slot="trigger" size="small" type="primary"><div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div></el-button>
                    <div class="el-upload__text"></div>
                    <el-button style="margin-left: 10px;" size="small" type="success" @click="getFile">获取文件</el-button>
                    <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>
                    <div slot="tip" class="el-upload__tip">可上传格式（jpg  jpeg png pdf doc docx xls xlsx）</div>
                </el-upload>
            </div>
        </div>
    </div>
</template>

<script>
    import insurance from '../../api/insurance';
    import 'dhtmlx-gantt'
    import {removeUser} from "../../api/api";
    export default {
        name: 'gantt',
        data () {
            // var checkProName = (rule, value, callback) => {if (!value) { return callback(new Error('请输入项目名称'));}else{callback(); }};
            // var checkProDescription = (rule, value, callback) => { if (!value) {return callback(new Error('请填写项目描述'));}else{callback();} };
            // var checkProAttribution = (rule, value, callback) => {if (!value) {return callback(new Error('请输入项目归属地点'));}else{callback();}};
            // var checkStartDate = (rule, value, callback) => {if (!value) { return callback(new Error('请选择开始时间'));}else{callback(); }};
            // var checkEndDate = (rule, value, callback) => {
            //     if (!value) { return callback(new Error('请选择结束时间'));}else{callback(); }
            // };
            // var checkDuration = (rule, value, callback) => {
            //     this.ruleForm.progress = value.replace(/[^0-9]*/g, '');
            //     if (!value) { return callback(new Error('请填写持续时间'));}else{callback(); }
            // };
            // var checkProgress = (rule, value, callback) => {if (!value) { return callback(new Error('请填写项目进度'));}else{callback(); }};
            // var checkHookURL = (rule, value, callback) => {if (!value) { return callback(new Error('请填写钉钉项目群 群机器人的webhook'));}else{callback(); }};
            return {
                arr1 : [],  // 第一级项目
                arr2 : [],  // 第二级项目
                arr3 : [],  // 第三级项目
                caozLev:3,  // 添加或修改已操作到的级别
                proId:1,
                hookURL:'',
                uploadFileUrl:'',
                location:'',
                fileListimg:[],
                fileList: [
                    // {name: 'food.jpeg', url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'},
                    // {name: 'food2.jpeg', url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'}
                ],
                userList:[],
                priorityList:[{key: 1, label: "一级"},{key: 2, label: "二级"}, {key: 3, label: "三级"}],
                fileListType : ["jpg", "jpeg", "png", "pdf", "doc", "docx", "xls", "xlsx"],
                dtable:{'height':document.body.clientHeight-120+'px'},
                addParams:{
                    "ID":'',
                    "projectName":'',
                    "text":'',
                    "Location":'',
                    "type":'',
                    "start_date": '',
                    "end_date":'',
                    "duration":'',
                    "progress":'',
                    "owner_id":'31',
                    "parent":'',
                    "priority":'',
                    "hookURL":'',
                    "operator":'',

                    // "id": 0,
                    // "projectName": "A项目15",
                    // "text":'测试项目',
                    // "Location":"杭州",
                    // "type": "project",
                    // "start_date": "08-02-2018 00:00",
                    // "end_date": "09-02-2018 00:00",
                    // "duration": 30,
                    // "progress": 0.4,
                    // "owner_id": "1",
                    // "parent": 1,
                    // "priority":1,
                    // "operator":"1"
                },
                // 验证
                // rules: {
                //     projectName: [
                //         { validator: checkProName, trigger: 'blur' }
                //     ],
                //     text: [
                //         { validator: checkProDescription, trigger: 'blur' }
                //     ],
                //     Location: [
                //         { validator: checkProAttribution, trigger: 'blur' }
                //     ],
                //     start_date: [
                //         { validator: checkStartDate, trigger: 'blur' }
                //     ],
                //     end_date: [
                //         { validator: checkEndDate, trigger: 'blur' }
                //     ],
                //     duration: [
                //         { validator: checkDuration, trigger: 'blur' }
                //     ],
                //     progress: [
                //         { validator: checkProgress, trigger: 'blur' }
                //     ],
                //     hookURL: [
                //         { validator: checkHookURL, trigger: 'blur' }
                //     ],
                // },
                tasks: {},
                loading:false,
                selectedTask: null,
                closeStu:false,
                selDataStu:false,
                messages: [],
                heightData: document.body.clientHeight-260,
                pickerOptions1: {
                    shortcuts: [{
                        text: '今天',
                        onClick(picker) {
                            picker.$emit('pick', new Date());
                        }
                    }, {
                        text: '昨天',
                        onClick(picker) {
                            const date = new Date();
                            date.setTime(date.getTime() - 3600 * 1000 * 24);
                            picker.$emit('pick', date);
                        }
                    }, {
                        text: '一周前',
                        onClick(picker) {
                            const date = new Date();
                            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
                            picker.$emit('pick', date);
                        }
                    }]
                },
            }
        },
        filters: {
            // 文件格式化
            formatFile(val){
                var f = val.url.split('.');
                if(f[f.length-1] == 'png' || f[f.length-1] == 'jpg' || f[f.length-1] == 'gif'){
                    return val.url;
                }else{
                    return '123';
                }
            },
            toPercent (val) {
                if(!val) return '0';
                return Math.round((+val) * 100)
            },
            niceDate (obj){
                return `${obj.getFullYear()}.${obj.getMonth()+1}.${obj.getDate()}`
            }
        },
        methods: {
            // 进度滑块
            formatTooltip(val) {
                return val / 100;
            },
            // 信息添加-------------
            submitForm(formName) {
                var that = this;
                that.$refs[formName].validate((valid) => {
                    if (valid) {}else{
                        this.altopen('请把信息填写完整！','warning');
                        return false;
                    }
                });
            },
            //  重置
            resetForm(formName) {
                this.$refs[formName].resetFields();
            },

            // 上传成功
            uploadSuccess(){
                this.$message({ message: '恭喜，上传成功！', type: 'success'});
            },
            //上传失败
            uploadError(){
                this.$message.error('上传失败！');
            },
            handleAvatarSuccess(res, file) {
                this.imageUrl = URL.createObjectURL(file.raw);
            },
            // 文件格式验证
            beforeAvatarUpload(file) {
                var blag = true;
                for(var i = 0; i< this.fileListType.length; i++){
                    var isType = file.name.split('.')[file.name.split('.').length-1];
                    if(!isType){
                        blag = false;
                    }
                }
                if(blag == false){
                    this.$message.error('上传只能是"  jpg jpeg png pdf doc docx xls xlsx  "格式!');
                    return isType;
                }
            },
            // 获取当前文件
            getFile(){
                var that = this;
                $.ajax(insurance.posturl+"file/allFiles?projID="+that.proId,{
                    headers: {'Content-Type': 'application/json;charset=UTF-8'},
                    'type': 'GET',
                    success:function (res) {
                        res = JSON.parse(res);
                        var list = [];
                        for(var i = 0; i<res.length; i++){
                            list.push({'name':res[i].fileName,'url':'http://192.168.0.120:8090/file/downloadFile/'+res[i].projID+'/'+res[i].fileName,'uid':res[i].ID});
                        }
                        that.fileList = list;
                    }
                });
            },
            // 文件删除
            delFile(uid,name){
                var that = this;
                $.ajax(insurance.posturl+"file/deleteFile/"+that.proId+"/"+uid+"/"+name,{
                    headers: {'Content-Type': 'application/json;charset=UTF-8'},
                    'type': 'POST',
                    success:function (res) {
                        if(res === 'SUCCESS'){
                            that.$message({
                                message: '删除成功！',
                                type: 'success'
                            });
                        }
                        that.getFile();
                    }
                });
            },
            // 文件上传
            submitUpload() {
                this.$refs.upload.submit();
                // location.reload();
            },
            // 文件删除
            handleRemove(file, fileList) {
                this.delFile(file.uid,file.name);
            },
            handlePreview(file) {
                var urls = file.url;
                var urls2 = urls.replace(/192.168.0.120:8090/g, "47.96.67.141:10045");
                window.open(urls2);
            },
            getData2(){
                this.getUser();
                this.getData();
            },
            ganttDemo(){
                this.$router.push({ path: '/ganttDemo' });
            },
            btnclose(blag){
                this.selDataStu = blag;
            },
            // 导出功能
            exportToExcel(){
                gantt.exportToExcel({
                    name:"document.xlsx",
                    columns:[
                        { id:"text",  header:"Title", width:150 },
                        { id:"start_date",  header:"Start date", width:250, type:"date" }
                    ],
                    server:"https://myapp.com/myexport/gantt",
                    visual:true,
                    cellColors:true
                })
            },
            $_initGanttEvents: function () {
                if(gantt.$_eventsInitialized)
                    return;
                gantt.attachEvent('onTaskSelected', (id) => {
                    let task = gantt.getTask(id);
                    this.selectedTask = task;
                    this.$emit('task-selected', task);
                    if(this.selectedTask != undefined || this.selDataStu != null)
                    {
                        this.selDataStu = true;
                    }
                    // this.getUser();
                    // gantt.serverList("staff", this.userList);
                });
                // 添加
                gantt.attachEvent('onAfterTaskAdd', (id, task) => {
                    this.$emit('task-updated', id, 'inserted', task);
                    task.progress = task.progress || 0;
                    this.selectedTask = task;
                    if(gantt.getSelectedId() == id) {
                        this.$emit('task-selected', task)
                    }
                    if(task.$level == 0 || task.$level > 2){
                        this.$message({message: '错误操作，只可添加第 2 3 级',type: 'warning'});
                    }else{
                        this.caozLev = task.$level+1;
                        this.addWays33(task,0);
                    }
                });


                // 修改
                gantt.attachEvent('onAfterTaskUpdate', (id, task) => {
                    this.$emit('task-updated', id, 'updated', task);
                    this.selectedTask = task;
                    this.caozLev = task.$level+1;
                    this.addWays33(task,parseInt(id));
                });
                // 刪除
                gantt.attachEvent('onAfterTaskDelete', (id) => {
                    this.$emit('task-updated', id, 'deleted');
                    this.delData(id);
                    if(!gantt.getSelectedId()) {
                        this.$emit('task-selected', null)
                    }
                });

                gantt.attachEvent('onAfterLinkAdd', (id, link) => {
                    console.log('----onAfterLinkAdd');
                    this.$emit('link-updated', id, 'inserted', link)
                });

                gantt.attachEvent('onAfterLinkUpdate', (id, link) => {
                    console.log('----onAfterLinkUpdate');
                    this.$emit('link-updated', id, 'updated', link)
                });

                gantt.attachEvent('onAfterLinkDelete', (id, link) => {
                    console.log('----onAfterLinkDelete');
                    this.$emit('link-updated', id, 'deleted')
                });
                gantt.$_eventsInitialized = true;
            },
            // 单级修改
            addWays33(params,id){
                this.caozLev = 2;
                this.paramsWay(params,id,id);
            },
            // 第二级进度修改   第三级添加或者修改
            addWayLev2(task,parent,isE){
                var arr2Index = 0;          // 第二级所有修改下标
                var arr2ProgressSum = 0;    // 第二级progress值
                var counts = 0;              // 计算在第二级下有几个第三级
                for(var i = 0; i<this.arr2.length; i++){  // 记录所要修改的第二级下标
                    if(this.arr2[i].id == parent){
                        arr2Index = i;
                    }
                }
                for(var i = 0; i<this.arr3.length; i++){ // 第二级 将子内容进度累加
                    if(this.arr3[i].parent == this.arr2[arr2Index].id ){
                        arr2ProgressSum = parseFloat(arr2ProgressSum)+parseFloat(this.arr3[i].progress);
                        counts = counts+1;
                    }
                }
                if(isE == 0){
                    arr2ProgressSum = parseFloat(arr2ProgressSum)+parseFloat(task.progress);
                    counts = parseFloat(counts)+1;
                }
                this.arr2[arr2Index].progress = arr2ProgressSum/parseFloat(counts);
                this.caozLev = 1;
                this.paramsWay(this.arr2[arr2Index],this.arr2[arr2Index].id);
            },
            // 第一级进度修改  第二级添加或者修改
            addWayLev1(task,parent){
                var arr1ProgressSum = 0;
                for(var i = 0; i<this.arr2.length; i++){ // 第二级 将子内容进度累加
                    arr1ProgressSum = parseFloat(arr1ProgressSum)+parseFloat(this.arr2[i].progress);
                }
                this.arr1[0].progress = parseFloat(arr1ProgressSum)/parseFloat(this.arr2.length);
                this.caozLev = -1;
                this.paramsWay(this.arr1[0],this.arr1[0].id);
            },
            // 赋值
            paramsWay(params,id,isE){
                if(params.progress > 1){
                    params.progress = 1;
                }
                this.addParams = JSON.stringify({
                    "ID":id,"projectName":params.projectName,
                    "text":params.text,
                    "Location":this.location,
                    "type":parseInt(params.$level).toString(),
                    "start_date": this.dateR(this.formatData(params.start_date)),
                    "end_date":this.dateR(this.formatData(params.end_date)),
                    "duration":parseInt(params.duration),
                    "progress":params.progress,
                    "owner_id":parseInt(params.owner_id),
                    "parent":parseInt(params.parent),
                    "priority":parseInt(params.priority),
                    "hookURL":this.hookURL,"operator":JSON.parse(sessionStorage.getItem('user')).id});
                this.updData(isE);
            },

            // 插件初始化
            initData(){
                // 周末突出
                var that = this;
                gantt.init(that.$refs.gantt);
                gantt.parse(that.tasks); // 初始化数据
            },
            initGantt(){
                gantt.templates.scale_cell_class = function (date) { if (date.getDay() == 0 || date.getDay() == 6) { return "weekend";} };
                // // 背景样式
                gantt.templates.grid_row_class = function (start_date, end_date, item) { if (item.progress == 0) return "red"; if (item.progress >= 1) return "green";};
                // // 背景样式
                gantt.templates.task_row_class = function (start_date, end_date, item) { if (item.progress == 0) return "red";if (item.progress >= 1) return "green";};
                // // 周末突出
                gantt.templates.task_cell_class = function (item, date) {if (date.getDay() == 0 || date.getDay() == 6) {return "weekend"}};
                // 弹窗选择数据
                gantt.serverList("staff",JSON.parse(window.localStorage.getItem('userList')));
                // 优先
                gantt.serverList("priority", [{key: 1, label: "一级"},{key: 2, label: "二级"}, {key: 3, label: "三级"}]);
                // gantt.config.work_time = true;    // 右侧不包括周六日
                // gantt.config.skip_off_time = true;
                // 弹窗样式
                gantt.config.grid_width = 500;
                gantt.config.grid_resize = true;
                gantt.config.open_tree_initially = true;
                // 弹窗名称设置
                gantt.config.duration_unit = "hour";
                gantt.config.duration_step = 24/7;
                gantt.config.scale_height = 20 * 3; // 弹窗时间 单位为H
                gantt.config.scale_unit = "day";
                gantt.config.date_scale = "%d日 周%D";
                gantt.config.min_column_width = 60;
                gantt.config.row_height = 30;
                // 左侧头部日期格式
                var weekScaleTemplate = function (date) {
                    // var dateToStr = gantt.date.date_to_str("%M%d日");
                    // var endDate = gantt.date.add(gantt.date.add(date, 1, "month"), -1, "day");
                    // return dateToStr(date) + " - " + dateToStr(endDate) + " " + weekNum(date);
                    // return dateToStr(date) + "   --   " + dateToStr(endDate);
                };
                gantt.config.subscales = [ {unit: "month", step: 1, date: "%F, %Y"},{unit: "week", step: 1, template: weekScaleTemplate}];
                gantt.config.subscales = [ {unit: "month", step: 1, date: "%Y年  %F "}];
                gantt.templates.progress_text = function (start, end, task) {
                    return "<span style='text-align:left;'>" + Math.round(task.progress * 100) + "% </span>";
                };
                gantt.templates.task_cell_class = function (task, date) {if (!gantt.isWorkTime(date)) return "week_end";return "";};
                var labels = gantt.locale.labels;
                labels.column_projectName = labels.section_projectName = "项目名称";
                labels.column_description = labels.section_description = "项目描述";
                labels.column_priority = labels.section_priority = "优先级别";
                labels.column_owner = labels.section_owner = "负责人员";
                labels.column_time = labels.section_time = "所需工时（H）";
                labels.column_progress = labels.section_progress = "项目进度";
                function byId(list, id) { for (var i = 0; i < list.length; i++) {if (list[i].key == id)return list[i].label || "";}return "";}
                // 左边菜单列表
                gantt.config.columns = [
                    {name: "projectName", label: "项目名称", tree: true, width: '*',resize:true, template: function (item) {
                            return "<div class='important'>" + item.projectName +"</div>";}},
                    {name: "owner",label: "人员",width: 50, align: "center",template: function (item) {
                            return byId(gantt.serverList('staff'), item.owner_id)}},
                    // return "xxx"
                    {name: "progress", label: "进度", align: "center", width: '50',template: function (item) {
                            if (parseFloat(item.progress)>= 1.0)return "100%"; if (parseFloat(item.progress)<= 0.0)return "0%";
                            return Math.round(parseFloat(item.progress) * 100) + "%";}
                    },
                    {name: "duration2", label: "工作量(时)", align: "center", width: '80', template: function (item) {
                            if(item.duration2 == 0 || item.duration2 == undefined){  return  item.duration+'时'}else{  return  item.duration2+'时'}}},
                    {name: "priority",label: "级别", align: "center", width:'40', template: function (item) {
                            return byId(gantt.serverList('priority'), item.priority)}},
                    {name: "add", width:30}
                ];
                // 弹窗 内容
                gantt.config.lightbox.sections = [
                    {name: "projectName", height:20, map_to: "projectName", type: "textarea", focus: true}, // 项目模块名称
                    {name: "progress", height:20, map_to: "progress", type: "textarea", focus: true},// 进度
                    {name: "priority", height:40, map_to: "priority", type: "select", options: gantt.serverList("priority")}, // 所属级别
                    {name: "owner",height:40, map_to: "owner_id", type: "select", options: gantt.serverList("staff")},
                    {name: "description", height:160, map_to: "text", type: "textarea", focus: true}, // 具体内容描述
                    {name: "time", type: "duration", map_to: "auto"},
                ];
                gantt.templates.rightside_text = function(start, end, task){ return byId(gantt.serverList('staff'), task.owner_id);};
                gantt.templates.task_class = function (start, end, task) {
                    var css = [];
                    if (task.$virtual || task.type == gantt.config.types.project)
                        css.push("summary-bar");
                    if(task.owner_id){
                        css.push("gantt_resource_task gantt_resource_" + task.owner_id);
                    }
                    return css.join(" ");
                };
                gantt.attachEvent("onLoadEnd", function(){
                    var styleId = "dynamicGanttStyles";
                    var element = document.getElementById(styleId);
                    if(!element){
                        element = document.createElement("style");
                        element.id = styleId;
                        document.querySelector("head").appendChild(element);
                    }
                    var html = [];
                    var resources = gantt.serverList("staff");
                    resources.forEach(function(r){
                        html.push(".gantt_task_line.gantt_resource_" + r.key + "{" +
                            "background-color:"+r.backgroundColor+"; " +
                            "color:"+r.textColor+";" +
                            "}");
                        html.push(".gantt_row.gantt_resource_" + r.key + " .gantt_cell:nth-child(1) .gantt_tree_content{" +
                            "background-color:"+r.backgroundColor+"; " +
                            "color:"+r.textColor+";" +
                            "}");
                    });
                    element.innerHTML = html.join("");
                });
            },
            // 后台数据修改
            updData(isE){
                var that = this;
                $.ajax(insurance.posturl+"proj/StorgeProj",{
                    'data': that.addParams,
                    headers: {'Content-Type': 'application/json;charset=UTF-8'},
                    'type': 'POST',
                    success:function (res) {
                        if(res === 'FAIL'){
                            if(that.addParams.ID == 0){
                                that.altopen('添加失败！','success');
                            }else{
                                that.altopen('修改失败！','success');
                            }
                        }else{
                            if(that.addParams.ID == 0){
                                that.altopen('添加成功！','success');
                            }else{
                                that.altopen('修改成功！','success');
                            }
                        }
                        if(that.caozLev == 2){
                            that.addWayLev2(JSON.parse(that.addParams),JSON.parse(that.addParams).parent,isE);
                        }else if(that.caozLev == 1){
                            that.addWayLev1(JSON.parse(that.addParams),JSON.parse(that.addParams).parent);
                        }else if(that.caozLev == -1){
                            location.reload();
                        }
                    }
                });
            },
            // 后台数据刪除
            delData(id){
                var that = this;
                $.ajax(insurance.posturl+"proj/deleteProj?projID="+id+"&operator="+JSON.parse(sessionStorage.getItem('user')).id,{
                    headers: {'Content-Type': 'application/json;charset=UTF-8'},
                    'type': 'POST',
                    success:function (res) {
                        location.reload();
                        // that.getData();
                        // that.initData();

                    }
                });
            },
            getData(){
                var that = this;
                that.tasks = {};
                $.ajax(insurance.posturl+"proj/projInfo?projID="+that.proId,{
                    headers: {'Content-Type': 'application/json;charset=UTF-8'},
                    'type': 'GET',
                    success:function (res) {
                        res = JSON.parse(res);
                        that.hookURL = res[0].hookURL;
                        that.location = res[0].Location;
                        that.arr1 = [];
                        that.arr2 = [];
                        that.arr3 = [];
                        var data = [];
                        for(var i = 0; i<res.length; i++){
                            var d = new Object();
                            if(res[i].type == '0'){   // 一级
                                d = {'id':res[i].ID,'projectName':res[i].projectName,'lev':0,'text':res[i].text,'owner_id':res[i].owner_id,'priority':res[i].priority,'progress':res[i].progress,'start_date':res[i].start_date,
                                    'duration':res[i].duration,'duration2':0,'end_date':res[i].end_date, 'parent':res[i].parent,"open": true,"type": "project"};
                                that.arr1.push(d);
                            }else if(res[i].type == '1'){ // 二级
                                d = {'id':res[i].ID,'projectName':res[i].projectName,'lev':1,'text':res[i].text,'owner_id':res[i].owner_id,'priority':res[i].priority,'progress':res[i].progress,'start_date':res[i].start_date,
                                    'duration':res[i].duration,'duration2':0,'end_date':res[i].end_date,'parent':res[i].parent,"open": true,"type": "project"};
                                that.arr2.push(d);
                            }else if(res[i].type == '2'){  // 三级
                                d = {'id':res[i].ID,'projectName':res[i].projectName,'lev':2,'text':res[i].text,'owner_id':res[i].owner_id,'priority':res[i].priority,'progress':res[i].progress,'start_date':res[i].start_date,
                                    'duration':res[i].duration,'duration2':res[i].duration,'end_date':res[i].end_date,'parent':res[i].parent,"open": true,"type": "project","render":"split","open": false,};
                                that.arr3.push(d);
                            }else if(res[i].type == '3'){  // 四级
                                d = {'id':res[i].ID,'projectName':res[i].projectName,'lev':3,'text':res[i].text,'owner_id':res[i].owner_id,'priority':res[i].priority,'progress':res[i].progress,'start_date':res[i].start_date,
                                    'duration':res[i].duration,'duration2':0,'end_date':res[i].end_date,'parent':res[i].parent,"open": true};
                            }
                            data.push(d);
                        }
                        that.duration2(that.arr3,data);
                    }
                });
            },
            // 第三级时间累加到第二级
            duration2(time3,data){
                for(var i = 0; i<this.arr2.length; i++){
                    var d = 0;
                    for(var k = 0; k<time3.length; k++){
                        if(time3[k].parent == this.arr2[i].id){
                            d = parseInt(d)+parseInt(time3[k].duration);
                        }
                    }
                    this.arr2[i].duration2 = d;
                }
                this.duration1(this.arr2,data);
            },
            // 第二级时间累加到第一级
            duration1(time2,data){
                var data1 = [];
                var d = 0;
                for(var k = 0; k<time2.length; k++){
                    if(time2[k].parent == this.arr1[0].id){
                        d = parseInt(d)+parseInt(time2[k].duration2);
                    }
                }
                this.arr1[0].duration2 = d;
                for(var i = 0; i<data.length; i++){
                    for(var k = 0; k<this.arr2.length; k++){
                        if(this.arr2[k].id == data[i].id){
                            data[i].duration2 = this.arr2[k].duration2;
                        }
                    }
                    if(this.arr1[0].id == data[i].id){
                        data[i].duration2 = this.arr1[0].duration2;
                    }
                }
                this.tasks.data = data;
                this.initData();
            },
            // 时间转换(月 - 日  颠倒)
            dateR(d){
                var dates = d.split('-');
                return dates[1] + '-' + dates[0] + '-' + dates[2];
            },
            dateR2(d){
                var dates = d.split('-');
                return dates[0] + '-' + dates[1] + '-' + dates[2];
            },
            // 获取用户列表
            getUser(){
                var that = this;
                $.ajax(insurance.posturl+"user/AllUsers?page=0&pageSize=200",{
                    headers: {'Content-Type': 'application/json;charset=UTF-8'},
                    'type': 'GET',
                    success:function (res) {
                        res = JSON.parse(res);
                        var data = [];
                        for(var i = 0; i<res.list.length; i++){
                            var d = {'key':res.list[i].id,'label':res.list[i].name};
                            data.push(d)
                        }
                        that.userList = data;
                    }
                });
            },

            // 公共弹框
            altopen(msg,type) {
                this.$notify({
                    type:type,
                    message: msg,
                    offset: 100,
                });
            },

            formatData(d){
                var d1 = new Date();
                if(d != undefined){
                    d1 = new Date(d);
                }
                var m = d1.getMonth()+1;
                var d = d1.getDate();
                if((d1.getMonth()+'').length <= 1){
                    m = '0'+m;
                }
                if((d1.getDate()+'').length <= 1){
                    d = '0'+d1.getDate();
                }
                return m + '-' + d + '-' + d1.getFullYear() + ' ' + d1.getHours() + ':' + d1.getMinutes();
            },
            getUser(){
                var that = this;
                $.ajax(insurance.posturl+"user/AllUsers?page=0&pageSize=200",{
                    headers: {'Content-Type': 'application/json;charset=UTF-8'},
                    'type': 'GET',
                    success:function (res) {
                        res = JSON.parse(res);
                        var datas = [];
                        for(var i = 0; i<res.list.length; i++){
                            datas.push({'value':res.list[i].id,'label':res.list[i].name});
                        }
                        that.options = datas;
                    }
                });
            },
        },
        // 销毁组件，返回刷新
        deactivated() {
            this.$destroy()
        },
        mounted () {
            var t = new Date;
            this.addParams.start_date = new Date(t.getFullYear(), t.getMonth(), t.getDate(), t.getHours(), t.getMinutes());
            this.addParams.end_date = new Date(t.getFullYear(), t.getMonth(), t.getDate()+1, t.getHours(), t.getMinutes());
            this.userList = JSON.parse(window.localStorage.getItem('userList'));
            this.$_initGanttEvents();
            this.initGantt();
            // this.proId = this.$route.query.ID;
            this.uploadFileUrl =insurance.posturl+"file/uploadFile?projID="+this.$route.query.ID;// 附件上传路径
            var seconds = 1;
            var time = setInterval(() => {
                if (seconds > 1) {
                    seconds = seconds - 1;
                } else {
                    this.getData();
                    this.getFile();
                    this.addParams.owner_id='31';
                    clearInterval(time);
                }
            },100);
        }
    }

</script>
<style>
    @import "~dhtmlx-gantt/codebase/dhtmlxgantt.css";
    .gantt_cell:nth-child(1) .gantt_tree_content{margin: 0px !important;}
    .el-upload-list__item.is-success:hover .el-icon-close{ position: absolute;top: 7px; right: 11px;}
    .el-upload-list__item.is-ready .el-icon-close{position: absolute;top: 7px; right:30px;}
    .el-upload{width: 350px;}
    .closebtns{position: absolute;right: 36px; top: 19px;background: rgb(0, 128, 192);color: rgb(255, 255, 255);font-size: 16px; width: 100px; line-height: 31px;z-index:3;text-align: center;}
    html, body {
        height: 100%;
        padding: 0px;
        margin: 0px;
        overflow: hidden;
    }

    .gantt_task_line.gantt_project{
        color:white;
    }

    .gantt_side_content{
        color:#333;
    }

    /*.summary-bar{*/
    /*font-weight: bold;*/
    /*}*/
    .gantt_grid_data .gantt_cell{}
    .gantt_resource_task .gantt_task_content{
        /*color:inherit;*/
    }

    .gantt_resource_task .gantt_task_progress{
        background-color:rgba(33,33,33,0.3);
    }

    .gantt_cell:nth-child(1) .gantt_tree_content{
        border-radius: 16px;
        width: 100%;
        height: 80%;
        /*margin: 5px 0;*/
    }
    .weekend {
        background: #f4f7f4;
    }

    .gantt_selected .weekend {
        background: #f7eb91;
    }
    .red .gantt_cell, .odd.red .gantt_cell,
    .red .gantt_task_cell, .odd.red .gantt_task_cell {
        background-color: #FDE0E0;
    }

    .green .gantt_cell, .odd.green .gantt_cell,
    .green .gantt_task_cell, .odd.green .gantt_task_cell {
        background-color: #BEE4BE;
    }
    .important {
        color: #666;
    }
    .container {
        height: 100%;
        width: 100%;
    }

    .left-container {
        overflow: hidden;
        position: relative;
        height: 100%;
    }

    .right-container {
        border-right: 1px solid #cecece;
        float: right;
        height: 100%;
        width: 340px;
        box-shadow: 0 0 5px 2px #aaa;
        z-index: 99 !important;
        position: fixed;
        background: #fff;
        right: 0px;
        padding-top: 35px;
    }
    .right-container .closebtn{
        float: right;
        margin-right: 15px;
        margin-top: 15px;
        color: rgb(105, 169, 208);
        width: 50px;
        height: 50px;
        position: absolute;
        top: 0px;
        right: 0px;
    }
    .gantt-messages {
        list-style-type: none;
        height: 50%;
        margin: 0;
        overflow-x: hidden;
        overflow-y: auto;
        padding-left: 5px;
    }

    .gantt-messages > .gantt-message {
        background-color: #f4f4f4;
        box-shadow:inset 5px 0 #d69000;
        font-family: Geneva, Arial, Helvetica, sans-serif;
        font-size: 14px;
        margin: 5px 0;
        padding: 8px 0 8px 10px;
    }

    .gantt-selected-info {
        border-bottom: 1px solid #cecece;
        box-sizing: border-box;
        font-family: Geneva, Arial, Helvetica, sans-serif;
        height: 50%;
        line-height: 28px;
        padding: 10px;
        position: fixed;
        background: #fff;
        z-index: 999;
    }

    .gantt-selected-info h2 {
        border-bottom: 1px solid #cecece;
    }

    .select-task-prompt h2{
        color: #d9d9d9;
    }
</style>
